
<template><div style="text-align:center">
  <el-button @click="preview = !preview" type="primary" size="mini" style="margin-bottom: 1em">
    <i :class="'fa fa-lg fa-eye' + (preview ? '' : '-slash')"></i> 切换预览
  </el-button></div>
  <el-form
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    label-width="100px"
    class="demo-ruleForm"
    size="mini"
    v-show="!preview"
  >
    <el-form-item label="标题" prop="title">
      <el-input v-model="ruleForm.title" maxlength="30" show-word-limit></el-input>
    </el-form-item>
    <el-form-item label="选择已有标签" prop="type">
      <el-select
        v-model="ruleForm.tags"
        multiple
        filterable
        allow-create
        default-first-option
        placeholder="请选择文章标签"
      >
        <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="添加新的标签">
      <el-tag
        :key="tag"
        v-for="tag in ruleForm.new_tags"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)"
        style="margin-right:1em;"
      >{{ tag }}</el-tag> 
      <el-input
        class="input-new-tag"
        v-if="inputVisible"
        v-model="inputValue"
        ref="saveTagInput"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      ></el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
    </el-form-item>
    <el-form-item label="目录" prop="category">
      <el-radio-group v-model="ruleForm.category">
        <el-radio
          v-for="category in categories"
          :key="category.id"
          :label="category.id"
        >{{ category.name }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="是否已删除">
      <el-switch
        v-model="ruleForm.is_deleted"
        active-color="#ff4949"
        inactive-color="#13ce66"
        active-text="已删除"
        inactive-text="未删除"
      ></el-switch>
    </el-form-item>
    <el-form-item label="是否私有">
      <el-switch
        v-model="ruleForm.is_private"
        active-color="#13ce66"
        inactive-color="#ff4949"
        active-text="私有"
        inactive-text="公有"
      ></el-switch>
    </el-form-item>
    <el-form-item label="内容" prop="content">
      <!-- <el-input
        type="textarea"
        v-model="ruleForm.content"
        show-word-limit
        maxlength="5000"
        :autosize="{ minRows: 5, maxRows: 20 }"
      ></el-input> -->
      <v-md-editor v-model="ruleForm.content" height="400px"></v-md-editor>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
  <div v-show="preview">
    <el-card>
      <template #header>
        <div style="text-align: left; font-size: 2em">
          [
          <span style="font-size: 0.8em">
            {{
              ruleForm.is_private ? "私有" : "公开"
            }}
          </span>
          ] {{ ruleForm.title }}
        </div>
      </template>
      <div>
        <el-row style="flex" justify="left" :gutter="10">
          <el-col :span="3" style="text-align: left">
            <i class="fa fa-tags" style="color: aqua"></i> 标签：
          </el-col>
          <el-col :span="21" style="text-align: left">
            <el-tag v-for="tag in ruleForm.tags" :key="tag.name" class="my-tag">{{ tag.name }}</el-tag>
          </el-col>
        </el-row>
        <el-row style="flex" justify="left">
          <el-col :span="3" style="text-align: left">
            <i class="fa fa-tags" style="color: lightgreen"></i>
            新添加的标签：
          </el-col>
          <el-col :span="21" style="text-align: left">
            <el-tag
              v-for="tag in ruleForm.new_tags"
              :key="tag"
              class="my-tag"
              type="success"
            >{{ tag }}</el-tag>
          </el-col>
        </el-row>
      </div>
      <!-- <div style="text-align: left; margin-top: 1em">{{ ruleForm.content }}</div> -->
      <v-md-preview :text="ruleForm.content"></v-md-preview>
    </el-card>
  </div>
</template>

<script>
import { getTags } from "../../api/tags";
import { getCategories } from "../../api/categories";
import { createArticle, updateArticle } from "../../api/articles";
import { ElMessage } from "element-plus";
export default {
  data() {
    return {
      preview: false,
      inputVisible: false,
      inputValue: "",
      id: null,
      ruleForm: {
        new_tags: [],
        title: "",
        tags: [],
        category: "",
        is_deleted: false,
        is_private: false,
        content: "",
      },
      rules: {
        title: [
          { required: true, message: "不能为空", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 30 个字符之间",
            trigger: "blur",
          },
        ],
        content: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
      tags: [],
      categories: [],
    };
  },
  mounted() {
    this.getTagList();
    this.getCategoryList();
    console.log("route", this.$route);
    let articleJson = this.$route.params.article;
    if (articleJson) {
      let articleObj = JSON.parse(articleJson);
      for (let tag of articleObj.tags) {
        tag.value = tag.id;
      }
      if (articleObj.category) articleObj.category = articleObj.category.id;
      this.ruleForm = articleObj;
      this.ruleForm.new_tags = [];
      console.log("ruleForm", articleObj);
      this.id = articleObj.id;
      delete this.ruleForm.created_at
      delete this.ruleForm.last_modified_at
      delete this.ruleForm.id
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("data", this.ruleForm);
          let articleData = Object.assign({}, this.ruleForm)
          let tags = []
          for (let tag of this.ruleForm.tags) {
            tags.push(tag.id)
          }
          articleData.tags = tags
          articleData.category_id = this.ruleForm.category
          delete articleData.category
          if (!this.id) {
            promise = createArticle(articleData).then(res => {
              ElMessage({
                showClose: true,
                message: "文件创建成功",
                type: "success"
              })
            })
          } else {
            promise = updateArticle(this.id, articleData).then(res => {
              this.ruleForm.title = res.data.title
              this.ruleForm.category = res.data.category.id
              this.ruleForm.is_deleted = res.data.is_deleted
              this.ruleForm.is_private = res.data.is_private
              this.ruleForm.content = res.data.content
              this.ruleForm.new_tags = []
              for (let tag of res.data.tags) {
                tag.value = tag.id
              }
              this.ruleForm.tags = res.data.tags//新添加的tag无法在选择框中显示，因为vue无法识别对象的改动
              console.log("form after update", this.ruleForm)
              ElMessage({
                showClose: true,
                message: "文件更新成功",
                type: "success"
              })
            })
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getTagList() {
      getTags().then((res) => {
        this.tags = res.data;
        for (let tag of this.tags) {
          tag.value = tag.id;
        }
      });
    },
    getCategoryList() {
      getCategories().then((res) => {
        this.categories = res.data;
      });
    },
    handleClose(tag) {
      this.ruleForm.new_tags.splice(this.ruleForm.new_tags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        console.log("before push new tags form", this.ruleForm)
        console.log("before push new tags", this.ruleForm.new_tags)
        this.ruleForm.new_tags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
  },
};
</script>

<style>
</style>
